<?php

use think\Loader;
use think\facade\Env;
use think\facade\Hook;
use think\facade\Route;

// 定义插件目录
define('ADDON_PATH', Env::get('root_path') . 'addons' . DIRECTORY_SEPARATOR);
//插件资源目录
define('ASSETS_PATH', Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'addons' . DIRECTORY_SEPARATOR);

define('DS', DIRECTORY_SEPARATOR);

// 定义插件路由,tp5.1需要手动指定controller的规则，否则会遇符号而止
Route::any('addons/:addon-:controller-:action', "\\addons\\library\\Route@execute")->pattern(['controller' => '[\w\_\.]+']);


// 如果插件目录不存在则创建
if (!is_dir(ADDON_PATH)) {
    @mkdir(ADDON_PATH, 0777, true);
}

// 注册插件类的根命名空间
Loader::addNamespace('addons', ADDON_PATH);
//安装插件管理
\think\facade\Middleware::add(function (\think\Request $request, \Closure $next) {
    $response = $next($request);
    \addons\install\Install::getInstance()->execute();
    return $response;
});

//加载配置中预加载文件
$addons_list = config('addons.');
unset($addons_list['pre_load']);
foreach ($addons_list as $name => $addon) {
    if (isset($addon['pre_load']) && !empty($addon['pre_load'])) {
        if (is_string($addon['pre_load'])) {
            $addon['pre_load'] = explode(',', $addon['pre_load']);
        }
        foreach ($addon['pre_load'] as  $file) {
            $file = ADDON_PATH . DIRECTORY_SEPARATOR . $name . DIRECTORY_SEPARATOR . $file;
            if (is_file($file)) {
                require_once $file;
            }
        }

    }
}

if (!function_exists('hook')) {
    /**
     * 处理插件钩子
     *
     * @param string $hook 钩子名称
     * @param mixed $params 传入参数
     * @return mixed
     */
    function hook($hook, $params = [])
    {
        $result = Hook::listen($hook, $params);
        if (count($result) > 0) {
            return $result;
        }
    }
}

if (!function_exists('get_addon_class')) {
    /**
     * 获取插件类的类名
     *
     * @param string $name 插件名
     * @param string $type 返回命名空间类型
     * @param string $class 当前类名
     * @return string
     */
    function get_addon_class($name, $type = 'hook', $class = null)
    {
        $name = Loader::parseName($name);
        // 处理多级控制器情况
        if (!is_null($class) && strpos($class, '.')) {
            $class = explode('.', $class);
            foreach ($class as $key => $cls) {
                $class[$key] = Loader::parseName($cls, 1);
            }
            $class = implode('\\', $class);
        } else {
            $class = Loader::parseName(is_null($class) ? $name : $class, 1);
        }
        switch ($type) {
            case 'controller':
                $namespace = "\\addons\\" . $name . "\\controller\\" . $class;
                break;
            default:
                $namespace = "\\addons\\" . $name . "\\" . $class;
        }
        return class_exists($namespace) ? $namespace : '';
    }
}

if (!function_exists('get_addon_config')) {
    /**
     * 获取插件类的配置文件数组
     *
     * @param string $name 插件名
     * @return array
     */
    function get_addon_config($name)
    {
        $class = get_addon_class($name);
        if (class_exists($class)) {
            $addon = new $class();

            return $addon->getConfig();
        } else {
            return [];
        }
    }
}


if (!function_exists('addon_url')) {
    /**
     * 插件显示内容里生成访问插件的url
     * @param $url 插件名/控制器/方法
     * @param array $param
     * @param bool|string $suffix 生成的URL后缀
     * @param bool|string $domain 域名
     * @return bool|string
     */
    function addon_url($url, $vars = [], $suffix = true, $domain = false)
    {
        list($addons, $controller, $action) = implode('/', $url);

        return url("@addons/{$addons}-{$controller}-{$action}", [], $suffix, $domain) . ($vars ? '?' . http_build_query($vars) : '');
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
               return copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
        return true;
    }

}

if (!function_exists('delDir')) {
    function delDir($dir)
    {
        if (!is_dir($dir)) {
            return true;
        }
        //先删除目录下的文件：
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    @unlink($fullpath);
                } else {
                    delDir($fullpath);
                }
            }
        }
        closedir($dh);
        //删除当前文件夹：
        if (@rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}
if (!function_exists('show_join')) {
    function show_join($table, $fk, $fk_val, $field)
    {
        static $tables;
        if (!$tables[$fk][$fk_val][$field]) {
            $tables[$fk][$fk_val][$field] = \think\Db::name($table)->where($fk, $fk_val)->value($field);
        }
        return $tables[$fk][$fk_val][$field];
    }
}